<?php
class system_controller_action_helper_login extends system_controller_action_helper_abstract {
	
	public function init() {
		
	}
	
	public function direct($args = array()) {
		$instance = system_passport_instance::getInstance();
		$session = $instance->getSession();
		if(!$session->getId()) {
			$this->_exitAndShow($args);
			return true;
		}
		$user = $instance->getUser();
		if(!$user->getCredential()) {
			$this->_exitAndShow($args, '请重新输入密码', 'passport');
			return true;
		}
		/**
		 * 安全登录验证
		 */
		if($session->getSecurity() && $user->getSecure() != $session->getSecurity()) {
			$session->logout();
			$this->_exitAndShow($args, '您设置了安全登录！我们检测到您的帐号已经在别处登录，您已被强行退出系统，请重新登录。');
			return true;
		}
		return false;
	}
	
	private function _exitAndShow($args = array(), $exception = null, $action = 'login') {
		if(isset($args[0]) && isset($args[0][0]) && isset($args[0][0]['ajax'])) {
			header('Content-type:application/json;charset=utf8');
			if($action == 'login') {
				$exception = '登录超时，请重新登录！';
			}
			echo json_encode(array('status' => 0, 'message' => $exception));
			exit;
		}
		$controller = $this->getActionController();
		$request = $controller->getRequest();
		$controller->view->exception = $exception ? new front_exception($exception) : null;
		$controller->view->referer = $this->getFrontController()->getInstance()
									->getRouter()
									->assemble($request->getControllerName() . '/' . $request->getActionName(), $request->getParams());
		$request->setControllerName('account')->setActionName($action)->setDispatched(false);
	}
}
